package com.qf.om.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(urlPatterns = "/codeImg")
public class CodeServlet extends HttpServlet {
    //    存储到session

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int height = 40;
        int width = 60;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//       获得一个图片的图层对象，在图层上绘制内容
        Graphics graphics = image.getGraphics();
//        设置图层颜色
        graphics.setColor(Color.ORANGE);
//        绘制矩形从0,0开始
        graphics.fillRect(0, 0, width, height);
//        绘制内容
        String code = codeContnet();
        req.getSession().setAttribute("code", code);
        System.out.println(code);
//        存放验证码生成时间
        req.getSession().setAttribute("code_time",System.currentTimeMillis());
//        重新设置字体颜色
        graphics.setColor(Color.RED);
//        设置文字样式
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 18));
//        写入内容和内容位置
        graphics.drawString(code, (int) (width * 0.08), (int) (height * 0.7));
//        编绘干扰线
        graphics.setColor(Color.BLUE);
        for (int i = 0; i < 10; i++) {
            graphics.drawLine((int) (Math.random() * width), (int) (Math.random() * height), (int) (Math.random() * width), (int) (Math.random() * height));
        }
//将图片输出给页面的img标签
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }

    //      生成验证码
    private String codeContnet() {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int number = random.nextInt(36);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
